﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TF.Access;
using System.Drawing;
using System.IO;
using log4net;

/// <summary>
/// Summary description for WebUtility
/// </summary>
public sealed class WebUtility
{
    private static readonly ILog log = LogManager.GetLogger(typeof(WebUtility));
    private WebUtility()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static bool IsLogin()
    {
        return HttpContext.Current.Session[WSLogin.USER_NAME] != null;
    }

    public static TF_UserProfile GetUserProfile()
    {
        TF_UserProfile ret = null;

        // check cookie first, if the cookie exists, the user login with out password, can get only
        HttpCookie cookie = 
            HttpContext.Current.Request.Cookies["LU"];
        if ( cookie!= null/* && cookie.Expires>DateTime.Now*/)
        {
            HttpContext.Current.Session[WSLogin.USER_NAME] = TF_UserProfile.Login(cookie.Value);
        }
        
        if (HttpContext.Current.Session[WSLogin.USER_NAME] != null)
        {
            ret = HttpContext.Current.Session[WSLogin.USER_NAME] as TF_UserProfile;
        }
        else
        {
            string localPath = HttpContext.Current.Request.Url.LocalPath.ToLower();
            // if the request page is index.aspx, no need to redirect
            if (localPath.IndexOf("index.aspx") >= 0 ||
                localPath.IndexOf("triplist.aspx") >= 0 ||
                localPath.IndexOf("tfuserprofile.aspx") >= 0 ||
                localPath.IndexOf("tripplan.aspx") >= 0 ||
                localPath.IndexOf("search.aspx") >= 0 ||
                localPath.IndexOf("places.aspx") >= 0 ||
                localPath.IndexOf("donkey.aspx") >=0)
            { }
            else
            {
                HttpContext.Current.Response.Redirect("Error.aspx");
            }
        }

        return ret;
    }

    public static bool SetUserProfileInSession(TF_UserProfile up)
    {
        bool ret = false;
        try
        {
            if (up == null)
            {
                HttpContext.Current.Session.Remove(WSLogin.USER_NAME);
                ret = true;
            }
            else
            {
                HttpContext.Current.Session[WSLogin.USER_NAME] = up;
                ret = true;
            }
        }
        catch (Exception ex)
        {
            // todo
            ret = false;
        }
        return ret;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="settingKey">key in web.config</param>
    /// <param name="folder"></param>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static int UploadPhoto(string settingKey, string folder, out string fileName)
    {
        int ret = -1;

        fileName = string.Empty;

        string uploadPath = string.Empty;
        //string fileSrc = string.Empty;

        if (HttpContext.Current.Request.Files.Count > 0 && 
            HttpContext.Current.Request.Files[0].ContentLength >0)
        {
            HttpPostedFile hpf = HttpContext.Current.Request.Files[0];
            if (!IsValidImageFile(HttpContext.Current.Request.Files[0]))
            {
                ret = 0;
            }
            else
            {
                if (hpf.ContentLength <= Convert.ToInt32(ConfigurationManager.AppSettings["ImageSize"]))
                {
                    TF_UserProfile userProfile = WebUtility.GetUserProfile();
                    if (userProfile != null)
                    {
                        try
                        {
                            fileName = Path.GetFileName(hpf.FileName);
                            fileName = fileName.Replace(fileName.Substring(0, fileName.IndexOf(".")), userProfile.Uid + DateTime.Now.ToString("yyyyMMddHHmmssffffff"));

                            //绝对路径
                            uploadPath = HttpContext.Current.Server.MapPath(
                                ConfigurationManager.AppSettings[settingKey]) + Path.DirectorySeparatorChar + 
                                userProfile.Uid.ToString() + Path.DirectorySeparatorChar + 
                                folder + Path.DirectorySeparatorChar +
                                fileName;
                            if (!Directory.Exists(uploadPath.Substring(0, uploadPath.LastIndexOf(Path.DirectorySeparatorChar))))
                            {
                                Directory.CreateDirectory(uploadPath.Substring(0, uploadPath.LastIndexOf(Path.DirectorySeparatorChar)));
                            }
                            //相对路径
                            //fileSrc = ConfigurationManager.AppSettings[settingKey] + "/" + fileName;
                            hpf.SaveAs(uploadPath);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex.Message, ex);
                            ret = 2;
                        }
                    }
                    else
                    {
                        //
                    }
                }
                else
                {
                    ret = 3;
                }
            }
        }
        else
        {
            ret = 1;
        }

        //if (string.IsNullOrEmpty(script))
        //{
        //    //Uploaded file is valid, now we can do whatever we like to do, copying it file system,
        //    //saving it in db etc.

        //    //Your Logic goes here

        //    //script = string.Format(SCRIPT_TEMPLATE, "上传成功.", "false", fileSrc);
        //    ret = -1;
        //}

        //Now inject the script which will fire when the page is refreshed.
        //ClientScript.RegisterStartupScript(this.GetType(), "uploadNotify", script);

        return ret;
    }

    private static bool IsValidImageFile(HttpPostedFile file)
    {
        if (file.ContentType.ToString().ToLower().IndexOf("image") < 0)
        {
            return false;
        }

        bool ret = false;
        try
        {
            using (Bitmap bmp = new Bitmap(file.InputStream))
            {
                ret = true;
            }
        }
        catch (ArgumentException)
        {
            //throws exception if not valid image
            ret = false;
        }

        return ret;


    }

    public static string Alert(string p)
    {
        return string.Format("<script>window.alert('{0}');</script>", p);
    }
}
